package com.flyzing.genl.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.flyzing.genl.dto.POFile;
import com.flyzing.genl.dto.ClazzProperty;
import com.flyzing.genl.po.ColumnPO;
import com.flyzing.genl.po.TablePO;
import com.flyzing.genl.util.GenConfigHelper;
import com.flyzing.genl.util.StringUtil;
import com.flyzing.genl.util.TemplateHelper;

/**
 * @author yaoguangyao
 * @Date 2020年12月30日
 */
public class GenPOFile implements IGenFile{

	@Override
	public void generate(TablePO table, List<ColumnPO> columns) {
		String packages = GenConfigHelper.getProperty("package.po");
		String clazzName = StringUtil.convertUnderline(table.getTableName(), true);
		String path = JAVA_ROOT_PATH 
				+ "/" + packages.replaceAll("\\.", "/") 
				+ "/" + clazzName + ".java";
		
		//判断是否需要重写，po默认重写
		boolean isOverride = Boolean.valueOf(GenConfigHelper.getProperty("override.po", "true"));
		File file = new File(path);
		if (file.exists() && !isOverride) {
			return;
		}
		
		List<ClazzProperty> properties = new ArrayList<>();
		Set<String> imports = new HashSet<>();
		if (columns != null && columns.size() > 0) {
			ClazzProperty property = null;
			for (ColumnPO column : columns) {
				property = ClazzProperty.getFromPO(column);
				properties.add(property);
				//java.lang.* 不必导入
				if (property.getPropertyType().indexOf("java.lang") < 0) {
					imports.add(property.getPropertyType());
				}
			}
		}
		
		POFile poFile = new POFile();
		poFile.setAuthor(AUTHOR);
		poFile.setCreateDate(DATE_FORMAT.format(new Date()));
		poFile.setPack(packages);
		poFile.setImports(imports);
		poFile.setClazzComment(table.getTableComment());
		poFile.setClazzName(clazzName);
		poFile.setProperties(properties);
		
		file.getParentFile().mkdirs();
		TemplateHelper.getInstance().process("PO", path, poFile);	
	}

}
